﻿using DeviceFaultPushService.MessagePushService.Models;
using DeviceFaultPushService.SystemService;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Text.Json;

namespace DeviceFaultPushService.MessagePushService.Communication;

public class SocketCommunication : ICommunication
{
    private object _lock = new();
    Socket socket;

    public bool IsConnected => isConnected;
    bool isConnected = false;

    public void SendSms(string phone, string message, out string results)
    {
        string strContent = phone + ":0:" + message;
        //2）编码方式：
        //取值‘0’0x30：文本发送，gbk编码格式
        //取值‘1’0x31：二进制数据
        //取值‘3’0x33: tts 语音电话
        //取值‘5’0x35：文本发送 unicde 编码格式 big-endian
        results = Send(strContent);
    }

    public void SendCall(string phone, string message, out string results)
    {
        string strContent = phone + ":3:" + message;
        //2）编码方式：
        //取值‘0’0x30：文本发送，gbk编码格式
        //取值‘1’0x31：二进制数据
        //取值‘3’0x33: tts 语音电话
        //取值‘5’0x35：文本发送 unicde 编码格式 big-endian
        results = Send(strContent);
    }

    public bool Connect()
    {
        SocketCommunicationModel socketCommunication = JsonSerializer.Deserialize<SocketCommunicationModel>(GetConfiguration.Configuration.PassagewayMessage);
        //创建TCP/IP Socket  
        socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        try
        {
            // 连接到服务器  
            socket.Connect(new IPEndPoint(IPAddress.Parse(socketCommunication.Ip), socketCommunication.Port));
            isConnected = true;
            return true;

        }
        catch (Exception)
        {
            isConnected = false;
            return false;
        }
    }

    private string Send(string message)
    {
        lock (_lock)
        {
            try
            {
                // 要发送的数据  
                byte[] data = Encoding.Default.GetBytes(message);
                // 发送数据  
                socket.Send(data);
                // 接收来自服务器的响应  
                byte[] receivedData = new byte[1024];

                int receivedBytes = socket.Receive(receivedData);
                // 将接收到的字节转换为字符串  
                string response = Encoding.Default.GetString(receivedData, 0, receivedBytes);

                return response;
            }
            catch (Exception ex)
            {
                isConnected = false;
                return ex.Message;
            }
        }
    }
    public void Disconnect()
    {
        if (socket.Connected)
        {
            socket.Shutdown(SocketShutdown.Both);
            socket.Close();
            isConnected = false;
        }
    }
}